package com.sgcc.dlsc.monitorredis.controller;

import com.alibaba.fastjson.JSON;
import com.sgcc.dlsc.monitorredis.config.TimeTask;
import com.sgcc.dlsc.monitorredis.model.bo.Group;
import com.sgcc.dlsc.monitorredis.util.WebsocketUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;

@ServerEndpoint(value = "/websocket/{param}")
@Component
public class MyWebSocket {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private static Map<String, List<MyWebSocket>> map = new HashMap<>();
    private List<MyWebSocket> webSockets;
    private String clusterName;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("param") String clusterName) {
        this.clusterName=clusterName;
        webSockets = map.computeIfAbsent(clusterName, K -> new ArrayList<>());
        webSockets.add(this);
        this.session = session;
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
        System.out.println("连接成功");
        BlockingQueue<List<Group>> queue = TimeTask.queueClusterMap.get(clusterName);
        if (queue ==null){
            sendInfo(clusterName+"集群不存在");
            return;
        }
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    List<Group> groupList = null;
                    try {
                        groupList = queue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String info = JSON.toJSONString(groupList);
                    sendInfo(info);
                }
            }
        });
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if ("@heart".equals(message)) {
            System.out.println("心跳检测");
        } else {
            System.out.println("来自客户端的消息----刷新时间：" + message);
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    private void sendInfo(String message) {
        for (MyWebSocket item : map.get(clusterName)) {
            try {
                item.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }


}